//
//  LCHomePictureView.swift
//  SinaWeiBo
//
//  Created by mac on 16/12/6.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import SDWebImage

//item的重用标志

let itemIndentifier = "itemIndentifier"
//Itme的间距
let itemMargin:CGFloat = 5
//ietm宽
private let wigth1 = (ScreenWidth - 2 * StatusItemMargin - 2 * itemMargin)/3

class LCHomePictureView: UICollectionView {
    
    //定义一个接口来接收传递过来的viewmodel
    var prictureList: [LCHomePictureModel]?{
        didSet{
                countLabel.text = "\(prictureList?.count ?? 0)"
            //计算collection的大小
                calculateSize(count: prictureList?.count ?? 0)
                //2设置item的图片
                reloadData()
            
        }
    }
    
    //懒加载一个label
    private lazy var countLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.red
        return label
    }()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: wigth1, height: wigth1)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
        
       
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    private func setupUI(){
        //注册cell
        self.register(LCHomePrictureCell.self, forCellWithReuseIdentifier: itemIndentifier)
        
        self.backgroundColor = UIColor.white
        //设置数据源代理
        dataSource = self
        
        addSubview(countLabel)
       
        
        countLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }

    }
    
    
    //MARK:计算collectionview的大小
    private func calculateSize(count: Int){
        //在计算collectionview大小的地方来判断当只有一张图片的时候来获取这张图片的原始大小
        if count == 1 {
            if let Url = prictureList?.first?.thumbnail_pic{
                //从本地加载下载的图片
                if let pricture = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey:Url){
                    
                    var imageSize = pricture.size
                
                    //MARK:判断图片宽度过窄，高度过长的情况
                    if imageSize.width < 80 {
                        let imageWidth:CGFloat = 80
                        //计算出高度
                        var imageHeight = imageWidth/imageSize.width * imageSize.height
                        
                        if imageHeight > 160 {
                            imageHeight = 160
                        }
                        
                        imageSize = CGSize(width: imageWidth, height: imageHeight)
                    }
                    
                    
                    //设置view的大小
                    self.snp_updateConstraints { (make) in
                        make.size.equalTo(imageSize)
                    }
                //MARK:设置item的大小，当设置item的内容的大小的同时需要设置item的大小
                    //  设置单张图片的条目的大小
                    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                    //  重写设置itemSize
                    flowLayout.itemSize = imageSize
                    
                //MARK:保证配图的大小和itemSize大小同步
                    self.layoutIfNeeded()
                }
            }
            
            return
        }
        

        //列数
        let colums = count > 3 ? 3 : count
        //行数
        let line = (count-1)/3 + 1
        //图片宽
        let viewWigth = CGFloat(colums) * wigth1 + CGFloat(colums-1) * itemMargin
        //图片高
        let viewHeight = CGFloat(line)*wigth1 + CGFloat(line-1)*itemMargin
        //图片大小
        let viewSize = CGSize(width: viewWigth, height: viewHeight)
        
        //在这个位置设置view的大小
        self.snp_updateConstraints { (make) in
            make.size.equalTo(viewSize)
        }
        
        //如果不是单张图片重写设置回去
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        //  重写设置itemSize
        flowLayout.itemSize = CGSize(width: wigth1, height: wigth1)
        //MARK:保证配图的大小和itemSize大小同步
        self.layoutIfNeeded()
    }
    
}
//collectiondatasource。数据源方法
extension LCHomePictureView:UICollectionViewDataSource{
    //1
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return prictureList?.count ?? 0
    }
    //2
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: itemIndentifier, for: indexPath) as! LCHomePrictureCell
        cell.urlList = prictureList?[indexPath.row]
        
        return cell
    }
    
}
class LCHomePrictureCell: UICollectionViewCell {
    
    //MARK: 接收数据来填充cell
    var urlList: LCHomePictureModel?{
        didSet{
            if let urlStr = urlList?.thumbnail_pic{
                prictureView.sd_setImage(with: URL(string:urlStr), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
         
        }
        
    }

    //  MARK: -- 懒加载
    private lazy var prictureView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  设置图片按照原始比例显示
        imageView.contentMode = .scaleAspectFill
        //  多余部分剪切掉
        imageView.clipsToBounds = true
        
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        addSubview(prictureView)
        prictureView.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
    }
    
}


